const app = getApp();

Page({
  data: {
    statusOptions: getApp().globalData.enums.statusOptions,
    record: null,
    couponOptions: {
      movie: '电影观看券',
      'bubble-tea': '奶茶兑换券',
      housework: '家务补偿券',
      massage: '按摩服务券'
    }
  },
  
  onLoad(options) {
    const id = options.id;
    const record = app.getRecordById(id);
    
    if (record) {
      this.setData({
        record: this.formatRecord(record)
      });
    } else {
      wx.showToast({
        title: '记录不存在',
        icon: 'error',
        duration: 2000,
        complete: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }
  },
  
  formatRecord(record) {
    const dateObj = new Date(record.date);
    const createdAtObj = new Date(record.createdAt);
    
    const formattedDate = `${dateObj.getFullYear()}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日`;
    const formattedDateTime = `${formattedDate} ${dateObj.getHours().toString().padStart(2, '0')}:${dateObj.getMinutes().toString().padStart(2, '0')}`;
    const formattedCreatedAt = `${createdAtObj.getFullYear()}-${(createdAtObj.getMonth() + 1).toString().padStart(2, '0')}-${createdAtObj.getDate().toString().padStart(2, '0')} ${createdAtObj.getHours().toString().padStart(2, '0')}:${createdAtObj.getMinutes().toString().padStart(2, '0')}`;
    
    // 冲突等级标签
    const conflictLabels = ['轻微', '低', '中等', '高', '严重'];
    const conflictLabel = conflictLabels[record.conflictLevel - 1] || '中等';
    
    // 状态文本
    const statusTexts = {
      resolved: '已解决',
      unresolved: '未解决',
      'in-progress': '进行中'
    };
    
    // 责任方文本
    const responsibilityTexts = {
      self: '自己',
      partner: '对方',
      both: '双方各半',
      other: '其他原因'
    };
    
    return {
      ...record,
      formattedDate,
      formattedDateTime,
      formattedCreatedAt,
      conflictLabel,
      statusText: statusTexts[record.status] || '已解决',
      responsibilityText: responsibilityTexts[record.responsibility] || '对方'
    };
  },
  
  // 状态变更处理（优化版）
  onStatusChange(e) {
    const { record, statusOptions } = this.data;

    // 阻止已解决记录的修改
    if (record.status === 'resolved') {
      wx.showToast({
        title: '已解决状态不可修改',
        icon: 'none'
      });
      return;
    }

    // 获取新状态
    const newStatus = statusOptions[e.detail.value].value;

    // 准备更新数据
    const updatedRecord = {
      ...record,
      status: newStatus,
      statusText: statusOptions.find(item => item.value === newStatus).label
    };

    // 更新全局数据
    if (app.updateRecord(record.id, updatedRecord)) {
      // 更新页面数据（保持格式化）
      this.setData({
        record: this.formatRecord(updatedRecord),
        statusIndex: e.detail.value
      });
      
      wx.showToast({
        title: '状态更新成功',
        icon: 'success'
      });
    } else {
      wx.showToast({
        title: '更新失败，请重试',
        icon: 'none'
      });
    }
  },
  updateDuration(e) {
    const { record } = this.data;
    const newDuration = e.detail.value;
  
    // 数据验证（可选）
    if (isNaN(newDuration) || newDuration < 0) {
      wx.showToast({
        title: '请输入有效时长',
        icon: 'none'
      });
      return;
    }
  
    // 准备更新数据
    const updatedRecord = {
      ...record,
      duration: Number(newDuration) // 确保为数字类型
    };
  
    // 更新全局数据
    if (app.updateRecord(record.id, updatedRecord)) {
      // 更新页面数据（保持格式化）
      this.setData({
        record: this.formatRecord(updatedRecord)
      });
    }
  },

  goBack() {
    wx.navigateBack();
  },
  
  deleteRecord() {
    wx.showModal({
      title: '删除记录',
      content: '确定要删除这条记录吗？此操作不可恢复。',
      success: (res) => {
        if (res.confirm) {
          const id = this.data.record.id;
          app.deleteRecord(id);
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500,
            complete: () => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1500);
            }
          });
        }
      }
    });
  },
  
  toggleCouponUse() {
    const record = this.data.record;
    
    if (record.couponUsed) {
      wx.showToast({
        title: '已使用的补偿券不可修改',
        icon: 'none'
      });
      return;
    }
  
    const updatedRecord = {
      ...record,
      couponStatus: !record.couponUsed ? 'used' : 'unused',
      couponUsed: !record.couponUsed
    };
    
    if (app.updateRecord(record.id, updatedRecord)) {
      this.setData({
        record: this.formatRecord(updatedRecord)
      });
    }
  },
  
  transferCoupon() {
    wx.showToast({
      title: '转让功能开发中',
      icon: 'none'
    });
  },
  
  shareRecord() {
    wx.showToast({
      title: '分享功能开发中',
      icon: 'none'
    });
  }
});